#include "PdeExplorer.h"


ACCB1 void ACCB2 myAVAppRegisterForPageViewDrawingProc(AVPageView pageView, AVDevRect* updateRect, void* data);

SelectionExplorer::SelectionExplorer(AVDoc avDoc)
	: _avDoc (avDoc)
{
	_pdDoc = AVDocGetPDDoc (_avDoc);

	AVAppRegisterForPageViewDrawing( myAVAppRegisterForPageViewDrawingProc, this);   
}

SelectionExplorer::~SelectionExplorer(void)
{
	AVAppUnregisterForPageViewDrawingEx(myAVAppRegisterForPageViewDrawingProc, this);
}

ACCB1 void ACCB2 myAVAppRegisterForPageViewDrawingProc(AVPageView pageView, AVDevRect* updateRect, void* data)
{
  SelectionExplorer* selectionExplorer = static_cast<SelectionExplorer*>(data);

  //see if right page view being updated
  if((selectionExplorer->_avDoc != AVPageViewGetAVDoc(pageView)) || 
	 (selectionExplorer->_pageNumber != AVPageViewGetPageNum(pageView)))
    return;

  //get scaled and scrolled rect coordinates
  AVDevRect rect;
  AVPageViewRectToDevice(pageView, &selectionExplorer->_selectRect, &rect);

  PDColorValueRec color;
  color.space = PDDeviceRGB;
  color.value[0] = 0;
  color.value[1] = 0;
  color.value[2] = ASInt32ToFixed(1);

  //set color
  AVPageViewSetColor(pageView, &color);

  //draw rect
  AVPageViewDrawRectOutline(pageView, &rect, 2, NULL, 0);
}

void SelectionExplorer::Redraw(AVPageView& pageView, ASFixedRect& rect)
{
	AVDevRect newRect;
    AVPageViewRectToDevice(pageView, &rect, &newRect);
    AVPageViewInvalidateRect(pageView, &newRect);
    AVPageViewDrawNow(pageView);
}

void SelectionExplorer::ScrollToRect(AVPageView& pageView, ASFixedRect& rect)
{
	AVDevRect newRect;
    AVPageViewRectToDevice(pageView, &rect, &newRect);
	AVPageViewScrollToRect ( pageView, &newRect, true, true, 5);
}

void SelectionExplorer::HiliteWord(int charOffset, ASFixedRect &rect)
{
	AVPageView pageView = AVDocGetPageView(_avDoc);

	ASFixedRect oldRect = _selectRect;

	_selectRect = rect;

	if(_pageChanged == false)
	{
		Redraw(pageView, oldRect);
	}
	_pageChanged = false;

	Redraw(pageView, rect);
	ScrollToRect(pageView, rect);

	//HiliteEntry hilite;
	//hilite.offset = (ASUns16)(_charOffset + charOffset);
	//hilite.length = 0;

	//// Highlight the requested word.
	//PDTextSelect textSelect = PDTextSelectCreatePageHilite (_pdPage, &hilite, 1);

	//PDTextSelect textSelect = PDDocCreateTextSelect (_pdDoc, _pageNumber, &rect);


	//AVDocSetSelection (_avDoc, ASAtomFromString("Text"), (void *)textSelect, true);
	//AVDocShowSelection (_avDoc);
}